package common;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import common.cache.CacheManager;

import play.cache.Cache;

import sun.net.www.content.audio.wav;

public class ArticleReader {

	private static ArticleReader instance = null;

	private ArticleReader() {
		// TODO Auto-generated constructor stub
	}

	public static synchronized ArticleReader getInstance() {

		if (instance == null)
			instance = new ArticleReader();
		return instance;
	}

	public Elements getArticle(String articleUrl, String sleepInterval) {

		Elements cleanArticle = null;
		String host = null;
		try {
			URL article = new URL(articleUrl);
			host = article.getHost();

			 Thread.sleep(Long.valueOf(sleepInterval));

			// socket timeout almamak için 10 sn delay verdim.
			Document articleWithJunk = Jsoup.connect(articleUrl)
					.timeout(10 * 1000).get();

			ArrayList<String> selectors = (ArrayList<String>) CacheManager.getJavaCacheItem(host);

			for (String string : selectors) {
				cleanArticle = articleWithJunk.select(string);
				if (!cleanArticle.isEmpty())
					break;
			}

		}
		catch (NullPointerException e) {
			System.out.println("Article Reader de Hata from " + host);
		}

		catch (SocketTimeoutException e) {
			System.out.println("------------------<HATA>------------");
			System.out.println("From " + articleUrl + " and hostUrl: " + host);
			System.out.println("------------------</HATA>------------");
		}
		catch (IOException e) {
			System.out.println("------------------<HATA>------------");
			System.out.println("From " + articleUrl + " and hostUrl: " + host);
			System.out.println(e.getMessage());
			System.out.println("------------------</HATA>------------");
			
		}
		catch (InterruptedException e) {
			System.out.println("------------------<HATA>------------");
			System.out.println(e.getMessage());
			System.out.println("------------------</HATA>------------");
			
		}
		return cleanArticle;
	}
}
